#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Henrique Teófilo <henriquetft@gmail.com>

"""
Script that collects informations about the host
using linux procfs and other cli tools
"""

import subprocess

def execute(cmd):
	p = subprocess.Popen([ cmd ], stdout=subprocess.PIPE, shell=True)
	r = p.communicate()
	stdout = r[0] and r[0] or ""
	return stdout


def fill_cpuinfo(info):
	# FIXME: simply read the file
	stdout = execute("cat /proc/cpuinfo")
	num_proc = 0
	clock_proc = 0
	for l in stdout.split('\n'):
		if l.startswith("processor"):
			num_proc += 1
		if l.startswith("cpu MHz"):
			clock = float(l.split(':')[1].strip())
			clock_proc = max(clock, clock_proc)
	info['TOTALCPU'] = num_proc
	info['CPUSPEED'] = clock_proc
	
	# cpu usage
	stdout = execute('top -bin1')
	for l in stdout.split('\n'):
		if l.startswith('Cpu(s):'):
			for x in l.split(','):
				if x.endswith('%id'):
					idle = float(x.split('%')[0].strip())
					info['FREECPU'] = idle * info['TOTALCPU'] / 100.0
					info['USEDCPU'] = info['TOTALCPU'] - info['FREECPU']


def fill_meminfo(info):
	# FIXME: get from /proc/meminfo
	stdout = execute("free -k")
	for l in stdout.split('\n'):
		if l.startswith('Mem:'):
			info["TOTALMEMORY"] = l.split()[1]
		elif l.startswith("-/+ buffers"):
			v= l.split()
			used, free = v[2], v[3]
			info['USEDMEMORY'] = used
			info['FREEMEMORY'] = free


def fill_netinfo(info):
	""" Gets NETTX and NETRX of all ifaces except lo """
	stdout = execute("cat /proc/net/dev")
	info['NETTX'] = 0
	info['NETRX'] = 0	
	for l in stdout.split('\n'):
		if l.find(':') != -1:
			ifline = l.split(':')
			iface = ifline[0].strip()
			if iface != 'lo':
				numbers = ifline[1].split()
				NETRX, NETTX =  int(numbers[0]), int(numbers[8])
				info['NETTX'] += NETTX
				info['NETRX'] += NETRX


################################################################################

if __name__ == "__main__":
	# initializing ...
	info = { 'HYPERVISOR' : 'vbox',
	         'TOTALCPU' : 0,
	         'CPUSPEED' : 0,
	         'TOTALMEMORY' : 0,
	         'FREEMEMORY' : 0,
	         'USEDMEMORY' : 0,
	         'USEDCPU' : 0,
	         'FREECPU' : 0,
	         'NETTX' : 0,
	         'NETRX' : 0,
	}
	
	# getting informations from host ...
	fill_cpuinfo(info)
	fill_meminfo(info)
	fill_netinfo(info)
	
	for k, v in info.iteritems():
		print "%s=%s" % (k, v)
